from urllib2 import urlopen
from lxml import objectify
from operator import attrgetter

url = 'http://www.boardgamegeek.com/xmlapi/geeklist/%s'
banned = ['Yahtzee Jr.',
          'Scrabble',
          'Scrabble Jr.',
          'Battleship',
          'Trivial Pursuit',
          'U-Build Monopoly',
          'Rack-O',
          'Laser Battle',]

class Geeklist(object):
    """Each GeekList object is composed of Games and Comments"""
    def __init__(self, id):
        xml = load_xml(id)
        tree = objectify.fromstring(xml)
        self.thumbs = tree.thumbs
        self.title = tree.title
        self.creator = tree.username
        self.data = tree
        for k, v in tree.items():
            setattr(self, k, v)

    @property
    def games(self):
        items = self.data.iterchildren(tag='item')
        games = []
        for item in items:
            game = Game(item, self)
            games.append(game)
        return games

    @property
    def by_thumbs(self):
        return sorted(self.games, key=attrgetter('thumbs'), reverse=True)

    @property
    def cleaned(self):
        games = self.games
        cleaned = [game for game in games if game.objectname not in banned]
        cutoff = [game for game in cleaned if game.thumbs > 30]
        return cutoff

class Game(object):
    """Each GeekList is made of Games. This is basically the part
    that we care the most about. A game will have many Comments on
    it, as well as a variety of attributes."""
    def __init__(self, game, geeklist):
        for k, v in game.items():
            setattr(self, k, v)
        self.thumbs = int(self.thumbs)
        self.url = 'http://www.boardgamegeek.com/geeklist/%s/item/%s#item%s' % (geeklist.id, self.id, self.id)

    def __repr__(self):
        return self.objectname.encode('utf-8')

def load_xml(id):
    xml = urlopen(url % id)
    xmlstr = xml.read()
    return xmlstr
